<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import Table from '@/components/Form/table'
import Pagination from '@/components/Form/Pagination'
import { getMaintainListAPI, addMaintainAPI, editMaintainAPI, getMaintainInfoAPI, delMaintainAPI } from '@/api/device'
import { useCommunityNameList } from '@/hooks/index.js'
import { useMaintaintList } from '@/hooks/maintain.js'
import uploadImg from '@/components/ImageUpload/uploadImg'
import { ElMessage } from 'element-plus';
import ImagePreview from '@/components/ImagePreview'

const communityList = useCommunityNameList()
const maintainList = useMaintaintList()

// 列表查询参数
const queryData = reactive({
  current: 1,
  pageSize: 6,
  next_maintain_time: '',
  last_maintain_time: '',
  community_code: '',
  device_code: ''
})
// 渲染列表
const list = ref([])
const total = ref(0)
const initData = async () => {
  // 发送请求
  let { data: { count, rows } } = await getMaintainListAPI(queryData)
  console.log({ data: { count, rows } })
  // 赋值
  list.value = rows.map(({ photo, ...item }) => ({ photo: import.meta.env.VITE_APP_BASE_IMG + (photo ? photo.split(',')[0] : '/public/dist/static/empty.1e2fbc24.png'), ...item }))
  total.value = count
}
onMounted(() => {
  initData()
})
const maintainTable = [
  { value: 'community.name', label: '小区名称' },
  { value: 'device.name', label: '设备名称' },
  { value: 'device_code', label: '设备编码' },
  { value: 'unit', label: '维修单位名称' },
  { value: 'contacts', label: '维修人名称' },
  { value: 'photo', label: '照片' },
  { value: 'contacts_tel', label: '联系方式' },
  { value: 'remark', label: '备注' },
  { value: 'last_maintain_time', label: '最后维护时间' },
  { value: 'next_maintain_time', label: '下次维护时间' }
]
// 查询
const onSearch = () => {
  // queryData.pageNum=1
  queryData.last_maintain_time = queryData.last_maintain_time !== '' ? queryData.last_maintain_time.map(item => +item).join(',') : queryData.last_maintain_time
  queryData.next_maintain_time = queryData.next_maintain_time !== '' ? queryData.next_maintain_time.map(item => +item).join(',') : queryData.next_maintain_time
  initData()
}
// 重置
const onReset = () => {
  Object.assign(queryData, {
    current: 1,
    pageSize: 6,
    next_maintain_time: '',
    last_maintain_time: '',
    community_code: '',
    device_code: ''
  })
  initData()
}
// 抽屉开关控制变量
const drawer = ref(false)
// 表单数据
const formData = reactive({
  community_code: '',
  contacts: '',
  contacts_tel: '',
  device_code: '',
  last_maintain_time: '',
  next_maintain_time: '',
  photo: '',
  remark: '',
  unit: ''
})
// 表单校验
const formRules = {
  community_code: [{ required: true, message: "请选择", trigger: "change" }],
  device_code: [{ required: true, message: "请选择", trigger: "change" }],
  unit: [{ required: true, message: "请输入", trigger: "blur" }],
  contacts: [{ required: true, message: "请输入", trigger: "blur" }],
  contacts_tel: [{ required: true, message: "请输入", trigger: "blur" }],
  last_maintain_time: [{ required: true, message: "请输入", trigger: "blur" }],
  next_maintain_time: [{ required: true, message: "请输入", trigger: "blur" }],
}
// 表单引用
const formRef = ref()
// 标题事件
const title = computed(() => {
  return formData.id ? '修改维修记录' : '新增维修记录'
}) 
// 抽屉关闭之前
const handleClose = () => {
  // 移除校验
  formRef.value.resetFields()
  // 重置表单
  Object.assign(formData, {
    community_code: '',
    contacts: '',
    contacts_tel: '',
    device_code: '',
    last_maintain_time: '',
    next_maintain_time: '',
    photo: '',
    remark: '',
    unit: ''
  })
  drawer.value = false
}
// 表单提交
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value.validate()
    // 处理数据
    // 将日期转为时间戳
    formData.remark = formData.remark !== '' ? formData.remark : '用户未备注'
    formData.last_maintain_time = +new Date(formData.last_maintain_time)
    formData.next_maintain_time = +new Date(formData.next_maintain_time)
    const data = toRaw(formData)
    // 发送请求
    formData.id ? await editMaintainAPI(data) : await addMaintainAPI(data)
    // 提示成功
    ElMessage.success('操作成功')
    // 关闭弹框
    drawer.value = false
    // 移除校验
    await formRef.value.resetFields()
    // 更新列表
    initData()
  } catch (error) {
    console.log(error)
  }
}
// 修改数据回显
const replyData = async (id) => {
  // 发送请求
  let { data } = await getMaintainInfoAPI(id)
  // console.log(data)
  Object.assign(formData, data)
  drawer.value = true
}
// 修改事件
const edit = (id) => {
  replyData(id)
}
// 删除事件
const del = async (id) => {
  // 发送请求
  await delMaintainAPI(id)
  // 提示成功
  ElMessage.success('删除成功')
  // 边缘问题
  if (queryData.pageNum > 1 && list.value.length === 1) queryData.pageNum--
  initData()
}
// 获取当前时间
const defaultTime = new Date()
</script>

<template>
  <div>
    <el-card>
      <b>维修记录管理</b> <b style="font-weight: 400;font-size:12px;">记录对资产设备的维修情况记录</b>
      <el-card>
        <!-- 搜索区域 -->
        <el-form label-width="100px" :inline="true" size="normal">
          <el-row :gutter="20">
            <el-col :span="7" :offset="0">
              <el-form-item label="小区名称">
                <el-select placeholder="请输入" v-model="queryData.community_code">
                  <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.code"
                    placeholder="请选择"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7" :offset="0">
              <el-form-item label="设备编码">
                <el-input placeholder="请输入" v-model="queryData.device_code"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="10" :offset="0">
              <el-form-item label="最后维护时间">
                <el-date-picker v-model="queryData.last_maintain_time" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width:250px">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="19" :offset="0">
              <el-form-item label="下次维护时间">
                <el-date-picker v-model="queryData.next_maintain_time" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width:250px">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="5" :offset="0">
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <br>
      <el-card>
        <!-- 工具区域 -->
        <el-row type="flex" justify="space-between">
          <div></div>
          <div>
            <el-button type="primary" @click="drawer = true">新增维修记录</el-button>
          </div>
        </el-row>
        <br>

        <!-- 表格区域 -->
        <Table :table="maintainTable" :tableData="list" @edit="edit" @del="del">
          <template #community.name="{ row }">{{ row.community?.name }}</template>
          <template #device.name="{ row }">{{ row.device?.name }}</template>
          <template #photo="{ row }">
            <div style="width:100%">
              <ImagePreview :src="row.photo" alt="" :width="50"></ImagePreview>
            </div>
          </template>
          <template #last_maintain_time="{ row }">{{ new Date(row.last_maintain_time).toLocaleString() }}</template>
          <template #next_maintain_time="{ row }">{{ new Date(row.next_maintain_time).toLocaleString() }}</template>
        </Table>

        <!-- 分页区域 -->
        <Pagination v-model:pageNum="queryData.current" v-model:pageSize="queryData.pageSize" :total="total"
          @initData="initData" />

        <!-- 新增、修改抽屉区域 -->
        <el-drawer size="50%" v-model="drawer" direction="rtl" :title="title" :before-close="handleClose">
          <el-form :model="formData" ref="formRef" :rules="formRules" label-width="140px" :inline="false" size="normal">

            <el-form-item label="小区编号" prop="community_code">
              <el-select v-model="formData.community_code" style="width: 50%">
                <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="设备名称" prop="device_code">
              <el-select v-model="formData.device_code" style="width: 50%">
                <el-option v-for="item in maintainList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="维修单位名称" prop="unit">
              <el-input v-model="formData.unit" style="width: 50%" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="维修人名称" prop="contacts">
              <el-input v-model="formData.contacts" style="width: 50%" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="维修人联系方式" prop="contacts_tel">
              <el-input v-model="formData.contacts_tel" style="width: 50%" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="最后一次维护时间" prop="last_maintain_time">
              <el-date-picker v-model="formData.last_maintain_time" type="date" :default-time="defaultTime"
                placeholder="请选择" style="width: 50%" />
            </el-form-item>

            <el-form-item label="下次维护时间" prop="next_maintain_time">
              <el-date-picker v-model="formData.next_maintain_time" type="date" :default-time="defaultTime"
                placeholder="请选择" style="width: 50%" />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark" style="width: 50%" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="售后照片" prop="photo">
              <!-- 放置上传图片 -->
              <uploadImg v-model:imgUrl="formData.photo" :limit="3" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit">确定</el-button>
              <el-button @click="handleClose">取消</el-button>
            </el-form-item>

          </el-form>

        </el-drawer>

      </el-card>
    </el-card>
  </div>
</template>

<style scoped></style>